<template>
  <!--  定价方法匹配规则模板 -->
  <div>
    <!-- 按钮与搜索 -->
    <el-row class="adjModelTemplate container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          exportIcon
          importIcon
          @search="searchForm.page=1,searchFunc()"
          @clear="
            (searchForm.adjCode = ''), (searchForm.adjName = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="addOrEditFunc('2')">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
            <el-button @click="addOrEditFunc('3')">查看</el-button>
          </template>

          <div slot="exportArea">
                  <!-- 导出操作区域 -->
              <el-button @click="exportExcel('1')"
              >导出模板</el-button>
              <el-button @click="exportExcel('2')"
              >导出数据</el-button> 
         </div>
          <!-- 导入 -->
          <div slot="importArea">
                  <!-- 导入操作区域 -->
                  <el-upload
                    accept=".xls, .xlsx"
                    ref="upload"
                    :multiple="false"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    action
                    :limit="1"
                    :http-request="uploadFile"
                  >
                    <el-button>导入</el-button>
                  </el-upload>
          </div>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="107px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="调整项编号：">
                <el-input
                  v-model="searchForm.adjCode"
                  style="width:150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="调整项名称：">
                <el-input
                  v-model="searchForm.adjName"
                  style="width:150px"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :key="item.prop"
                >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>
        <!-- 列表 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="adjCode"
            label="调整项编号"
            :show-overflow-tooltip="true"
            v-if="columnState[0]"
          ></el-table-column>
          <el-table-column
            prop="adjName"
            label="调整项名称"
            :show-overflow-tooltip="true"
            v-if="columnState[1]"
          ></el-table-column>
          <el-table-column
            prop="adjType"
            label="类型"
          
            v-if="columnState[2]"
            :formatter="formatAdjType"
          ></el-table-column>
          <el-table-column
            prop="seqNum"
            label="调整项使用字段序号"
            :show-overflow-tooltip="true"
            v-if="columnState[3]"
          ></el-table-column>
          <el-table-column
            prop="trackDateType"
            label="跟踪日期类型"
            :show-overflow-tooltip="true"
            v-if="columnState[4]"
            :formatter="formatTrackDateType"
          ></el-table-column>
          <el-table-column
            prop="countWay"
            label="计算方式"
            :show-overflow-tooltip="true"
            v-if="columnState[5]"
            :formatter="formatCountWay"
          ></el-table-column>

          <el-table-column
            prop="lockDiffFlag"
            label="是否利差锁定项"
            :show-overflow-tooltip="true"
            v-if="columnState[6]"
            :formatter="row => (row.lockDiffFlag == 1 ? '是' : '否')"
          ></el-table-column>
          <el-table-column
            prop="insertWay"
            label="插值方式"
            :show-overflow-tooltip="true"
            v-if="columnState[7]"
            :formatter="formatInsertWay"
          ></el-table-column>
          <el-table-column
            prop="fundingFlag"
            label="是否BreakFund纳入项"
            :show-overflow-tooltip="true"
            v-if="columnState[8]"
            :formatter="row => (row.lockDiffFlag == 1 ? '是' : '否')"
          ></el-table-column>
          <el-table-column
            prop="ruleTemplate.elementFieldNames"
            label="规则字段"
            :show-overflow-tooltip="true"
            v-if="columnState[9]"
          ></el-table-column>

          <el-table-column
            prop="creator"
            label="创建人"
            :show-overflow-tooltip="true"
            v-if="columnState[10]"
          ></el-table-column>
          <el-table-column
            prop="createdTm"
            :show-overflow-tooltip="true"
            label="创建时间"
            sortable
            v-if="columnState[11]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            :show-overflow-tooltip="true"
            label="修改人"
            sortable
            v-if="columnState[12]"
            :formatter="row => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            :show-overflow-tooltip="true"
            label="修改时间"
            sortable
            v-if="columnState[13]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
     <!-- 新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="ruleTemplateDi"
      width="60%"
      top="2%"
    >
      <adjRuleModeForm ref="adjRuleTemplateForm" :operateType="operateType" :saveForm="adjRuleFormData" 
      @backReSearch="searchFunc()"/>
      <div slot="footer">
         <el-button @click="saveFunc" v-if="operateType != 3">确 定</el-button>
         <el-button @click="ruleTemplateDi = false">取 消</el-button>
       </div>
    </el-dialog>
  </div>
</template>

<script>
import { ruleTemplate,adjRule } from "@/api/index";
import { getDict } from "@/api/getDict";
import adjRuleModeForm from './adjRuleModel_form'
import moment from "moment";
export default {
  //定义数据
  data() {
    return {
      // 列隐藏依据数据
      textData: [
        { prop: "adjCode", label: "调整项编号", disabled: true },
        { prop: "adjName", label: "调整项名称", disabled: true },
        { prop: "adjType", label: "类型", disabled: true },
        { prop: "seqNum", label: "调整项使用字段序号", disabled: true },
        { prop: "trackDateType", label: "跟踪日期类型", disabled: true },
        { prop: "countWay", label: "计算方式", disabled: true },
        { prop: "lockDiffFlag", label: "是否利差锁定项", disabled: true },
        { prop: "insertWay", label: "插值方式", disabled: true },
        { prop: "fundingFlag", label: "是否BreakFund纳入项", disabled: true },
        { prop: "ruleTemplate", label: "规则字段", disabled: true },
        { prop: "creator", label: "创建人", disabled: true },
        { prop: "createdTm", label: "创建时间", disabled: true },
        { prop: "modifier", label: "修改人", disabled: true },
        { prop: "modifiedTm", label: "修改时间", disabled: true }
      ],
      // 显示的列
      checkList: [],
      countWayList:[],
      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        adjCode: "",
        adjName: ""
      },
      total: 0,
      tableData: [],
     
      //弹窗标识
      ruleTemplateDi: false,
      //新增编辑弹出框名称
      titleName: "",
      //操作标识
      operateType: 1,
      //当前选中数据
      adjId: "",
      adjCode: "",
      adjName: "",
      adjRuleFormData:{
        adjId:"",
        adjCode:"",
        adjName:"",
        adjType:"",
        countWay:"",
        trackDateType:"",
        seqNum:"",
        insertWay:"",
        fundingFlag:"",
        lockDiffFlag:"",
        creator:"",
        createdTm:"",
        ruleTemplate: {
              ruleTemplateFields:[]
        }
      }
    }
  },
  //组件引入
  components: {
    adjRuleModeForm
  },
  //创建初始化
  created() {
    this.checkListInit();
  },
  mounted() {
    this.searchFunc();
    this.getCountWayListDict();
  },
  //监控数值变化
  watch: {
    ruleTemplateDi(){
      this.searchFunc(); 
    }
  },
  //运算
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  provide() {
    return{
      closeRuleTemplateDi:this.closeRuleTemplateDi
    }
  },
  methods: {
    //查询
    searchFunc() {
      let data = this.searchForm;
      
      ruleTemplate.adjDefFindAll(data).then(res => {
        if (res.code === 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
        }
      });
    },
    closeRuleTemplateDi() {
      this.ruleTemplateDi = false;
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
          this.$refs.multipleTable.clearSelection()
      }
      this.$refs.multipleTable.toggleRowSelection(row, true)
    },
    //事件转换
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    //新增、编辑 
    addOrEditFunc(val) {
      this.operateType = val;
      this.titleName = "添加调整项定义信息";
      if (val === '1') {
          for(let k in this.adjRuleFormData){
           if(k!=='ruleTemplate') this.adjRuleFormData[k] =""
          }
          this.adjRuleFormData.ruleTemplate= {
              ruleTemplateFields:[]
          }	
          this.adjRuleFormData.fundingFlag = "0";
          this.adjRuleFormData.lockDiffFlag = "0";
          this.ruleTemplateDi = true;
          this.$nextTick(()=>{// 清除内部form
              this.$refs.adjRuleTemplateForm.searchModelFunc()
          })
      } else if (val === '2' || val === '3') {
          let selection = this.$refs.multipleTable.selection;
          if (selection.length < 1) {
            return this.$message.warning("请选择一条数据");
          } else if (selection.length > 1) {
            return this.$message.warning("只能选择一条数据");
          } else {
            if(val === '2'){
              this.titleName = "编辑调整项定义信息";
              let data = { 
                ids: selection.map(v => v.adjId)
              };
              ruleTemplate.adjDefIsDelete(data)
              .then(res => {
                if (res.code == 200) {
                  if (res.data == '1') {
                    return this.$message.warning("该模板正在使用中，不允许编辑！");
                  }
                }
              })
            } else {
              this.titleName = "查看调整项定义信息";
            } 
            
              this.adjRuleFormData.adjId = selection[0].adjId;
              this.adjRuleFormData.adjCode = selection[0].adjCode;
              this.adjRuleFormData.adjName = selection[0].adjName;
              this.adjRuleFormData.adjType = selection[0].adjType;
              this.adjRuleFormData.countWay = selection[0].countWay;
              this.adjRuleFormData.trackDateType = selection[0].trackDateType;
              this.adjRuleFormData.seqNum = selection[0].seqNum;
              this.adjRuleFormData.insertWay = selection[0].insertWay;
              this.adjRuleFormData.fundingFlag = selection[0].fundingFlag;
              this.adjRuleFormData.lockDiffFlag = selection[0].lockDiffFlag;
              this.adjRuleFormData.creator = selection[0].creator;
              this.adjRuleFormData.createdTm = selection[0].createdTm;
              this.$nextTick(()=>{// 清除内部form
                  this.$refs.adjRuleTemplateForm.searchModelFunc()
              })
              this.ruleTemplateDi = true;
          }
      }
    },
    //新增保存方法：
     saveFunc() {
      this.$refs.adjRuleTemplateForm.saveAdjTemplate();
    },

    //format转换
    formatAdjType(row){
      if (row.adjType == "1") {
        return "风险性";
      } else if (row.adjType == "2") {
        return "内生性";
      } else if (row.adjType == "3") {
        return "政策性";
      }
    },
     getCountWayListDict() {
      getDict("ftp_count_way").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.countWayList = res.datas;
          }
        }
      });
    },
    formatCountWay(row){
      return this.$getLabel(row.countWay, this.countWayList);
    },
    formatTrackDateType(row){
       if (row.trackDateType == "0") {
        return "跟踪起息日";
      } else if (row.trackDateType == "1") {
        return "跟踪数据日期";
      } else if (row.trackDateType == "2") {
        return "跟踪上次重定价日";
      }
    },
    formatInsertWay(row){
      if (row.insertWay == "1") {
        return "不插值";
      } else if (row.adjType == "2") {
        return "线性插值";
      }
    },
    //删除
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的模板数据");
      }
      let data = { 
        ids: selection.map(v => v.adjId)
      };
      ruleTemplate.adjDefIsDelete(data).then(res => {
        if (res.code == 200) {
          if (res.data == '1') {
            return this.$message.warning("该模板正在使用中，无法进行删除");
          } else {
            this.$confirm("您确定要删除选中模板吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                ruleTemplate.adjDefRemove(data).then(res => {
                  if (res.code == 200) {
                    this.$message.success("删除成功");
                    this.searchFunc();
                  } else {
                    this.$message.error(res.message || "删除失败");
                  }
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除"
                });
              });
          }
        } else {
          this.$message.error(res.message || "删除失败");
        }
      });
      
    },
    //导出文件
    exportExcel(tmpFlag) {

      let param = {
        hasTemplete: tmpFlag, //1为导出模板
        adjCode: this.searchForm.adjCode,  
        adjName: this.searchForm.adjName
      };

      adjRule
        .exp(param)
        .then((res) => {
          if (res) {
            var filename = decodeURI(res.headers["content-disposition"]).split("=")[1];
            let contenttype =
              filename.substring(filename.lastIndexOf("."), filename.length) === "xlsx"
                ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
                : "application/vnd.ms-excel;charset=utf-8";
            const content = res.data;
            const blob = new Blob([content], {
              type: contenttype,
            });
            let url = window.URL.createObjectURL(blob);
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
          }
        })
        .catch(function (error) {
          console.log(error);
          // this.$message.error("导出失败！");
        });
    },
     // 上传文件之前的钩子
    beforeUpload(file) {
      let name = file.name;
      let type = name.substring(name.lastIndexOf("."), name.length);
      if (type === ".xls" || type === ".xlsx") {
        return true;
      } else {
        this.$message.warning("只能选择xls或者xlsx格式的文件上传");
        return false;
      }
    },
     // 上传文件
    uploadFile(item) {
      let form = new FormData();
      // 文件对象
      form.append("excelFile", item.file);
      // 发送请求
      adjRule.imp(form)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
          this.$refs.upload.clearFiles();
        })
        .catch((err) => {
          this.$refs.upload.clearFiles();
        });
    },





  }
};
</script>


<style lang="scss" scoped>
.buessinessEleTable .el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}
</style>